<?php
session_start();
require("../includes/dbInfo.php");

$receiverID = $_POST['receiverID'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$senderID = $_POST['senderID'];
$groupIDs = $_POST['groupID'];

// check to see if the form is valid 
# form security goes here
if( $subject == "" ) {
    $subject = "(No Subject)";
}

if( $groupIDs ) {
    // for every group get the members of that group
    foreach( $groupIDs AS $g ) {
        $users_sql = mysql_query("SELECT userID from groupMembers where groupID = '$g'") 
            or die(mysql_error());
        // now send to each of these users
        while ($row = mysql_fetch_array($users_sql)) {
            $sql = mysql_query("INSERT INTO messages  
            (messageID, senderID, receiverID, subject, message, timestamp, readStatus) 
            VALUES (NULL, '$senderID', '$row[userID]', '$subject', '$message', NULL, 'UNREAD')")
            or die(mysql_error());
        }
    }
}

if( $receiverID ) {
    // insert query
    foreach ($receiverID AS $r) {
        $sql = mysql_query("INSERT INTO messages  
           (messageID, senderID, receiverID, subject, message, timestamp, readStatus) 
        VALUES (NULL, '$senderID', '$r', '$subject', '$message', NULL, 'UNREAD')")
        or die(mysql_error());
    }
}    
// redirect away from post page.
header('location: inbox.php');
?>